import vm from '../main'

//封装LocalStorage过期控制存储代码
export function setLocalStorage(key,value,expire){
  var curTime = new Date().getTime();
  localStorage.removeItem(key)
  localStorage.setItem(key,JSON.stringify({data:value,time:curTime + expire}));
}

//封装LocalStorage过期控制获取代码
export function getLocalStorage(key){
  var data = localStorage.getItem(key)
  var dataObj = JSON.parse(data)
  if(dataObj){
    if (new Date().getTime() > dataObj.time) {
      localStorage.removeItem(key)
      console.log('存储'+key+'的LocalStorage信息已过期')
      return false
    }else{
      var dataObjDatatoJson = dataObj.data
      return dataObjDatatoJson;
    }
  }
}

//封装LocalStorage过期控制删除代码
export function delLocalStorage(key){
  localStorage.removeItem(key)
}

//获取cookie（封装APP无法使用Cookie）
export function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg))
    return (arr[2]);
  else
    return null;
}

//设置cookie,增加到vue实例方便全局调用（封装APP无法使用Cookie）
export function setCookie (name, value, expire) {
  var exdate = new Date();
  exdate.setTime(exdate.getTime() + expire);
  document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ";expires=" + exdate.toGMTString());
};

//删除cookie（封装APP无法使用Cookie）
export function delCookie (name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null)
    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};

//制保留2位小数，如：2，会在2后面补上00.即2.00
export function toDecimal2(x) {
  var f = parseFloat(x);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(x*100)/100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}

export function message(params){
  let type = ''
  switch (params.type) {
    case 'success':type = 'success';break
    case 'warning':type = 'warn';break
    case 'info':type = 'text';break
    case 'error':type = 'cancel';break
    default:type = 'text';break
  }
  vm.$vux.toast.show({
    text: params.message,
    type: type,
    time: params.time?params.time:2000
  })
}

export function Trim(str,is_global){//去掉字符串中所有空格(包括中间空格,需要设置第2个参数为:g)
  var result;
  result = str?str.replace(/(^\s+)|(\s+$)/g,""):'';
  if(is_global && is_global.toLowerCase() == "g"){
    result = result.replace(/\s/g,"");
  }
  return result;
}
